package com.futer.ssm.controller;

import com.alibaba.fastjson.JSONObject;
import com.futer.ssm.model.*;
import com.futer.ssm.service.ItemService;
import com.futer.ssm.service.LibraryService;
import com.futer.ssm.service.Service;
import com.futer.ssm.service.UserService;
import com.futer.ssm.util.CheckNameAndEmail;
import com.futer.ssm.util.GetRandWord;
import com.futer.ssm.util.SendEmail;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import org.apache.neethi.All;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MediaType;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/futer")
//@Api(value = "测试信息", tags = {"测试相关接口"})//swagger控制器说明注解
@Api(value = "用户信息", description = "用户信息", produces = MediaType.APPLICATION_JSON)
public class FuterController {


    @Resource
    private UserService userService;
    @Resource
    private ItemService item;
    @Resource
    private LibraryService libraryService;
    @Resource
    private Service service;
    private Producer kaptchaProducer=null;


    public boolean checkUser(HttpSession session){
        if (session.getAttribute("user")==null || session==null){
            return false;
        }
        return true;
    }

    @RequestMapping(value="/index")
    public String index(HttpServletRequest request, HttpSession session,Model model){

        //返回用户名到页面
        try{
            if (session.getAttribute("user")==null){
                List<Setting> list=this.service.getSetting(new SettingExample());
                model.addAttribute("config",list.get(0));
                return "sysUi/loginview";
            }

            //==========================获取用户信息========================
            AllAppExample applicationExample=new AllAppExample();
            AllAppExample.Criteria criteria=applicationExample.createCriteria();
            criteria.andHideEqualTo(0);
            criteria.andCanuseEqualTo(1);
            criteria.andDesktopEqualTo(1);
            List<AllApp> applications=this.service.getAllApp(applicationExample);

            AllApp home = null;

            //获取首页信息
            int homeIndex = 0;
            for (int i=0;i<applications.size();i++){
                if (applications.get(i).getHome()==1){
                    home = applications.get(i);
                    homeIndex = i;
                }
            }

            //获取数组第零项
            AllApp first = applications.get(0);

            //设置首页为数组的第零项
            applications.set(0,home);
            applications.set(homeIndex,first);

            model.addAttribute("application",applications);
            //==========================获取用户信息End========================


            if (home!=null){
                model.addAttribute("home",home);
            }

            List<Setting> list=this.service.getSetting(new SettingExample());
            model.addAttribute("config",list.get(0));

            return "sysUi/index";
        }catch (Exception e){
            List<Setting> list=this.service.getSetting(new SettingExample());
            model.addAttribute("config",list.get(0));
            return "sysUi/loginview";
        }
    }

    //搜索用户
    @RequestMapping(value = "/checkInfo",method = RequestMethod.POST)
    @ResponseBody
    public String checkInfo(HttpServletRequest request,HttpServletResponse response,@RequestBody Login login,HttpSession session){
        //返回用户名到页面
        try{
            String userName = login.getName();
            String password = login.getPassword();
            String code = login.getCode();

            UserExample userExample=new UserExample();
            UserExample.Criteria criteria1=userExample.createCriteria();
            criteria1.andNameEqualTo(login.getName());
            criteria1.andActivityEqualTo(1);
            criteria1.andEnableEqualTo(1);
            User user=(this.userService.getUserByName(userExample)).get(0);

            String currentCode = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

            if (userName.equals(user.getName()) && password.equals(user.getPassword()) && currentCode.equalsIgnoreCase(code)){
                session.setAttribute("name",userName);
                session.setAttribute("password",password);
                session.setAttribute("id",user.getId());
                session.setAttribute("type",user.getType());
                session.setAttribute("user",user);
            }else{
                if (!userName.equals(user.getName()) || !password.equals(user.getPassword())){
                    return JSONObject.toJSONString("账号或密码错误");
                }else if (!code.equals(currentCode)){
                    return JSONObject.toJSONString("验证码错误");
                }

                return JSONObject.toJSONString("用户已被禁用或账号尚未激活");
            }

            /*if (session.getAttribute("user")==null){
                return JSONObject.toJSONString("登录失败");
            }*/


            return JSONObject.toJSONString("登录成功");
        }catch (Exception e){
            return JSONObject.toJSONString("用户已被禁用或账号尚未激活");
        }
    }


//    登录
    @RequestMapping("/login")
    public String login(HttpServletRequest request,HttpSession session,Model model){
        //如果已存在用户，则直接进行登录操作，无需跳转到登录界面
        if (session.getAttribute("user")!=null){
            model.addAttribute("user",session.getAttribute("user"));
            AllAppExample applicationExample=new AllAppExample();
            AllAppExample.Criteria criteria=applicationExample.createCriteria();
            criteria.andHideEqualTo(0);
            criteria.andDesktopEqualTo(1);
            criteria.andCanuseEqualTo(1);
            List<AllApp> applications=this.service.getAllApp(applicationExample);
            model.addAttribute("application",applications);

            List<Setting> list=this.service.getSetting(new SettingExample());
            model.addAttribute("config",list.get(0));

            //激活邮件已发送
            if (request.getParameter("statu")!=null){
                model.addAttribute("register","邮件已发送，请到邮箱中激活账号");
            }

            //已成功找回密码
            if (request.getParameter("successChangePwd")!=null){
                model.addAttribute("successChangePwd",request.getParameter("successChangePwd"));
            }

            //添加所有应用到界面，用于显示应用区域
            List<AllApp> show=this.service.getAllApp(new AllAppExample());
            model.addAttribute("show",show);
            return "sysUi/index";
        }


        List<Setting> list=this.service.getSetting(new SettingExample());
        model.addAttribute("config",list.get(0));
        return "sysUi/loginview";
    }

    //首页
    @RequestMapping(value = "home")
    public String home(HttpServletResponse response,HttpServletRequest request,Model model,HttpSession session){
        return "sysUi/home";
    }

//    商品列表
    @RequestMapping(value = "/market",method = RequestMethod.GET)
    public String market(HttpServletRequest request,Model model,HttpSession session){
        if (session==null || session.getAttribute("user")==null){
            model.addAttribute("login","login");
        }else {
            int page=1;
            if (request.getParameter("page")!=null){
                page=Integer.parseInt(request.getParameter("page"));
            }
            PageHelper.startPage(page, 30);
            List<Item> productDetails = item.getAllList(new ItemExample());

            PageInfo<Item> p = new PageInfo<Item>(productDetails);

            model.addAttribute("item",p.getList());
            model.addAttribute("page",p.getNavigatepageNums());
            model.addAttribute("allPage",p.getPages());
            model.addAttribute("currentPage",p.getPageNum());
        }

        return "/market";
    }

//    我的页面
    @RequestMapping("/my")
    public String my(HttpServletRequest request,Model model,HttpSession session){
        if (!checkUser(session)){
            model.addAttribute("login","login");
        }
        return "/my";
    }

//    购物车
    @RequestMapping(value ="/shoppingCat",method = RequestMethod.GET)
    public String shoppingCat(HttpServletRequest request,Model model,HttpSession session){
        if (!checkUser(session)){
            model.addAttribute("login","login");
        }else {

            int page=1;
            if (request.getParameter("page")!=null){
                page=Integer.parseInt(request.getParameter("page"));
            }
            PageHelper.startPage(page,14);

            ShoppingCatExample shoppingCatExample=new ShoppingCatExample();
            ShoppingCatExample.Criteria criteria=shoppingCatExample.createCriteria();
            criteria.andUsernameEqualTo("libowu");
            List<ShoppingCat> shoppingCats=this.service.getAllShoppingCat(shoppingCatExample);
            PageInfo<ShoppingCat> info=new PageInfo<>(shoppingCats);

            model.addAttribute("shoppingCat",info.getList());
            model.addAttribute("page",info.getNavigatepageNums());
            model.addAttribute("currentPage",info.getPageNum());
            model.addAttribute("allPage",info.getPages());
        }


        return "/shoppingCat";
    }

//    商品详情
    @RequestMapping(value = "/itemDetail",method = RequestMethod.GET)
    public String home(HttpServletRequest request,Model model,HttpSession session){
        if (!checkUser(session)){
            model.addAttribute("login","login");
        }else {
            Item item=this.item.getItem(request.getParameter("name"));

            CommentExample commentExample=new CommentExample();
            CommentExample.Criteria criteria=commentExample.createCriteria();
            criteria.andObjectnameEqualTo(item.getName());

            PageHelper.startPage(1,10);
            List<Comment> comment=this.item.getAllComment(commentExample);
            PageInfo<Comment> commentPageInfo=new PageInfo<Comment>(comment);

            ShoppingCatExample shoppingCatExample=new ShoppingCatExample();
            ShoppingCatExample.Criteria criteria1=shoppingCatExample.createCriteria();
            criteria1.andUsernameEqualTo("libowu");
            criteria1.andObjectnameEqualTo(item.getName());

            CollectExample collectExample=new CollectExample();
            CollectExample.Criteria criteria2=collectExample.createCriteria();
            criteria2.andObjectnameEqualTo(item.getName());
            criteria2.andUsernameEqualTo("libowu");

            BorrowExample borrowExample=new BorrowExample();
            BorrowExample.Criteria criteria3=borrowExample.createCriteria();
            criteria3.andObjectnameEqualTo(item.getName());
            criteria3.andUsernameEqualTo("libowu");

            List<ShoppingCat> shoppingCats=this.service.getAllShoppingCat(shoppingCatExample);
            List<Collect> collectList=this.service.getCollect(collectExample);
            List<Borrow> borrows=this.service.getAllBorrow(borrowExample);


            if (shoppingCats.size()==0){
                model.addAttribute("shopping",null);
            }else {
                model.addAttribute("shopping",shoppingCats.get(0));
            }

            if (collectList.size()==0){
                model.addAttribute("collect",null);
            }else {
                model.addAttribute("collect",collectList.get(0));
            }

            if (borrows.size()==0){
                model.addAttribute("borrow",null);
            }else {
                model.addAttribute("borrow",borrows.get(0));
            }

            model.addAttribute("item",item);
            model.addAttribute("comment",commentPageInfo.getList());
        }

        return "/itemDetail";
    }

//    购买动作
    @RequestMapping(value = "/buy",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ResponseBody
    public String buy(HttpServletRequest request,Model model,@RequestBody Library library,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

       String objectName=library.getObjectname();
       String type=library.getType();
       String userName=library.getUsername();

       library.setBuytime(new Date(System.currentTimeMillis()));

       //获取当前商品库存是否足够
           Item item=this.item.getItem(objectName);
           int result=-100;
           if (item.getLesscount()-1>0){

               //如果库足够则库存减1
               Item i=new Item();
               i.setName(objectName);
               i.setLesscount(item.getLesscount()-1);
               result=this.item.updateItem(i);

               //将购买的商品记录到library表格中去
               if (result==1){
                   int temp=this.libraryService.buyObject(library);

                   //重新获取商品信息
                   item=this.item.getItem(objectName);
               }
           }

       String back= JSONObject.toJSONString(item);

       return back;
    }

//    收藏
    @RequestMapping(value = "/collect",method = RequestMethod.POST)
    @ResponseBody
    public String collect(@RequestBody Collect collect,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        collect.setCollecttime(new Date(System.currentTimeMillis()));

        CollectExample collectExample=new CollectExample();
        CollectExample.Criteria criteria=collectExample.createCriteria();
        criteria.andObjectnameEqualTo(collect.getObjectname());
        criteria.andUsernameEqualTo(collect.getUsername());
        List<Collect> collectList=this.service.getCollect(collectExample);

        if (collectList.size()==0){
            int result=this.service.collect(collect);
            String back=JSONObject.toJSONString(result);
            return back;
        }else {
            int result=-10;
            String back=JSONObject.toJSONString(result);
            return back;
        }

    }

    //    借阅
    @RequestMapping(value = "/borrow",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ResponseBody
    public String borrow(HttpServletRequest request,Model model,@RequestBody Borrow borrow,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        //获取用户是否收藏了次物品
        BorrowExample borrowExample=new BorrowExample();
        BorrowExample.Criteria criteria=borrowExample.createCriteria();
        criteria.andObjectnameEqualTo(borrow.getObjectname());
        criteria.andUsernameEqualTo(borrow.getUsername());
        List<Borrow> borrows=this.service.getAllBorrow(borrowExample);



        int result=0;
        borrow.setCount(1);
        borrow.setBorrowdate(new Date(System.currentTimeMillis()));
        borrow.setOverdate(new Date(System.currentTimeMillis()+2678400l));
        if (borrows.size()==0){

            //查询库存是否足够
            Item item=this.item.getItem(borrow.getObjectname());
            String back="";
            if (item.getLesscount()-1>=0){
                result=this.service.borrowObject(borrow);

                //借阅成功后库存减1
                if (result==1){
                    Item re=new Item();
                    re.setLesscount(item.getLesscount()-1);
                    re.setName(borrow.getObjectname());
                    int reSave=this.item.updateItem(re);

                }

                //重新获取借阅后的商品情况
                Item reGet=this.item.getItem(borrow.getObjectname());
                back=JSONObject.toJSONString(reGet);
            }else {
                result=-20;
                back=JSONObject.toJSONString(result);
            }


            return back;
        }else {
            result=-10;
            String back=JSONObject.toJSONString(result);
            return back;
        }
    }


    //添加进购物车
    @RequestMapping(value = "/shoppingCat",method = RequestMethod.POST)
    @ResponseBody
    public String shoppingCat(@RequestBody ShoppingCat shoppingCat,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        shoppingCat.setAdddate(new Date(System.currentTimeMillis()));

        ShoppingCatExample shoppingCatExample=new ShoppingCatExample();
        ShoppingCatExample.Criteria criteria=shoppingCatExample.createCriteria();
        criteria.andObjectnameEqualTo(shoppingCat.getObjectname());
        criteria.andUsernameEqualTo(shoppingCat.getUsername());
        List<ShoppingCat> collectList=this.service.getAllShoppingCat(shoppingCatExample);

        if (collectList.size()==0){
            int result=this.service.addShoppingCat(shoppingCat);
            String back=JSONObject.toJSONString(result);
            return back;
        }else {
            int result=-10;
            String back=JSONObject.toJSONString(result);
            return back;
        }
    }


    //删除购物车物品
    @RequestMapping(value = "/removeShoppingCat",method = RequestMethod.POST)
    @ResponseBody
    public String removeShoppingCat(HttpServletRequest request,Model model,@RequestBody ShoppingCat shoppingCat,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        ShoppingCatExample shoppingCatExample=new ShoppingCatExample();
        ShoppingCatExample.Criteria criteria=shoppingCatExample.createCriteria();
        criteria.andObjectnameEqualTo(shoppingCat.getObjectname());
        criteria.andUsernameEqualTo(shoppingCat.getUsername());
        int result=this.service.removeShoppingCat(shoppingCatExample);
        String back=JSONObject.toJSONString(result);
        return back;
    }


    //收藏夹
    @RequestMapping(value = "/collectList",method = RequestMethod.GET)
    public String collectList(HttpServletRequest request,Model model,HttpSession session){
        if (!checkUser(session)){
            model.addAttribute("login","login");
        }else {
            int page=1;
            if (request.getParameter("page")!=null){
                page=Integer.parseInt(request.getParameter("page"));
            }
            PageHelper.startPage(page,14);

            CollectExample collectExample=new CollectExample();
            CollectExample.Criteria criteria=collectExample.createCriteria();
            criteria.andUsernameEqualTo("libowu");
            List<Collect> collect=this.service.getCollect(collectExample);


            if (collect.size()==0){
                model.addAttribute("collect",null);
                model.addAttribute("page",new int[]{1});
                model.addAttribute("currentPage",1);
                model.addAttribute("allPage",1);
            }else {
                PageInfo<Collect> info=new PageInfo<>(collect);
                model.addAttribute("collect",info.getList());
                model.addAttribute("page",info.getNavigatepageNums());
                model.addAttribute("currentPage",info.getPageNum());
                model.addAttribute("allPage",info.getPages());
            }
        }



        return "/collect";
    }

    //删除购物车物品
    @RequestMapping(value = "/removeCollect",method = RequestMethod.POST)
    @ResponseBody
    public String removeCollect(HttpServletRequest request,Model model,@RequestBody Collect collect,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        CollectExample collectExample=new CollectExample();
        CollectExample.Criteria criteria=collectExample.createCriteria();
        criteria.andObjectnameEqualTo(collect.getObjectname());
        criteria.andUsernameEqualTo(collect.getUsername());
        int result=this.service.removeCollect(collectExample);
        String back=JSONObject.toJSONString(result);
        return back;
    }


    //跳转到添加应用界面
    @RequestMapping(value = "/addApplication",method = RequestMethod.GET)
    public String addApplication(HttpServletRequest request,Model model,HttpSession session){
        if (!checkUser(session)){
            model.addAttribute("login","login");
        }

        AllApp allApp=new AllApp();
        if (request.getParameter("name")!=null){
            String name=request.getParameter("name");
            String img=request.getParameter("img");
            String url=request.getParameter("url");
            int type=Integer.parseInt(request.getParameter("type"));


            AllApp application=new AllApp();
            application.setCreatedate(new Date(System.currentTimeMillis()));
            application.setAppimg(img);
            application.setAppurl(url);
            application.setAppname(name);
            application.setHide(type);

            model.addAttribute("appInfo",application);
            model.addAttribute("statu",request.getParameter("result"));
        }else{
            model.addAttribute("appInfo",null);
            model.addAttribute("statu",null);
        }

        return "sysUi/addApplication";
    }

    //点击添加应用界面的“添加”按钮
    @RequestMapping(value = "/addApplicationSubmit",method = RequestMethod.POST)
    public String addAppSub(HttpServletRequest request, Model model, HttpSession session, RedirectAttributes attr){
        if (!checkUser(session)){
            model.addAttribute("login","login");
        }else {
            String baseImagePath = "img/appLogo/";
            String name=request.getParameter("appName");
            String img=request.getParameter("appLogo");
            String url=baseImagePath + request.getParameter("appImg");
            String appUrl=request.getParameter("appUrl");
            int type=Integer.parseInt(request.getParameter("type"));


            AllAppExample allApp=new AllAppExample();
            AllAppExample.Criteria criteria=allApp.createCriteria();
            criteria.andAppnameEqualTo(name);
            List<AllApp> applications=this.service.getAllApp(allApp);

            AllAppExample example=new AllAppExample();
            AllAppExample.Criteria criteria1=example.createCriteria();
            criteria1.andAppurlEqualTo(appUrl);
            List<AllApp> allApps=this.service.getAllApp(example);

            AllApp application=new AllApp();
            application.setCreatedate(new Date(System.currentTimeMillis()));
            application.setAppimg(url);
            application.setAppname(name);
            application.setAppurl(appUrl);
            application.setDesktop(type);
            application.setCreatedate(new Date(System.currentTimeMillis()));
            application.setCreateuser( ((User)(session.getAttribute("user"))).getName() );
            application.setMark(url.replaceAll("/",""));

            //检查是否存在此应用
            application.setCreatedate(new Date(System.currentTimeMillis()));
            int result=0;
            if (applications.size()==0 && allApps.size()==0){
                result=this.service.addApplication(application);
            }else {
                //存在此名称的应用
                if (applications.size()!=0){
                    result=-10;
                }else if (allApps.size()!=0){
                    result=-20;
                }
            }

            attr.addAttribute("name",name);
            attr.addAttribute("img",img);
            attr.addAttribute("url",url);
            attr.addAttribute("type",type);
            attr.addAttribute("result",result);
        }

        return "redirect:/futer/addApplication";
    }

    //刷新应用界面
    @RequestMapping(value = "/reFreshApp",method = RequestMethod.POST)
    @ResponseBody
    public String reFreshApp(HttpServletRequest request,Model model,@RequestBody Info info){

        AllAppExample applicationExample=new AllAppExample();
        AllAppExample.Criteria criteria=applicationExample.createCriteria();
        if (info.getType().equals("add")){
            criteria.andHideEqualTo(0);
            criteria.andCanuseEqualTo(1);
            criteria.andAppnameEqualTo(info.getName());
        }else {
            criteria.andHideEqualTo(0);
            criteria.andCanuseEqualTo(1);
        }


        List<AllApp> applications=this.service.getAllApp(applicationExample);
        String back=JSONObject.toJSONString(applications);
        model.addAttribute("application",applications);
        return back;
    }

    //退出登录与注销登录
    @RequestMapping(value = "/loginOut")
    public String loginOut(HttpServletRequest httpServletRequest,Model model){
        HttpSession session = httpServletRequest.getSession();
        session.invalidate();

        List<Setting> result=this.service.getSetting(new SettingExample());
        model.addAttribute("config",result.get(0));
        return "sysUi/loginview";
    }

    //框架设置
    @RequestMapping(value = "/setting")
    public String setting(HttpServletRequest httpServletRequest,Model model,HttpSession session){
        if (!checkUser(session)){
            model.addAttribute("login","login");
        }else {
            User user=(User) (httpServletRequest.getSession()).getAttribute("user");
            List<Setting> result=this.service.getSetting(new SettingExample());
            model.addAttribute("user",user);
            model.addAttribute("config",result.get(0));
        }

        return "sysUi/setting";
    }

    //保存框架设置
    @RequestMapping(value = "/saveSetting",method = RequestMethod.POST)
    @ResponseBody
    public String saveSetting(@RequestBody Setting setting,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        int result=this.service.updateSetting(setting);
        return JSONObject.toJSONString(result);
    }

    //重新加载配置文件
    @RequestMapping(value = "/reLoadCss",method = RequestMethod.POST)
    @ResponseBody
    public String reLoadCss(HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        List<Setting> result=this.service.getSetting(new SettingExample());
        return JSONObject.toJSONString(result.get(0));
    }


    //应用设置界面
    @RequestMapping(value = "/appSetting",method = RequestMethod.GET)
    public String appSetting(HttpServletRequest request,Model model,HttpSession session){
        if (session.getAttribute("user")==null){
            model.addAttribute("login","login");
        }else {
            int page=1;
            if (request.getParameter("page")!=null){
                page=Integer.parseInt(request.getParameter("page"));
            }
            PageHelper.startPage(page,14);

            AllAppExample allAppExample=new AllAppExample();
            AllAppExample.Criteria criteria=allAppExample.createCriteria();
            allAppExample.setOrderByClause("type");
            List<AllApp> allApp=this.service.getAllApp(allAppExample);


            //获取界面样式
            List<Setting> list=this.service.getSetting(new SettingExample());
            model.addAttribute("config",list.get(0));

            if (allApp.size()==0){
                model.addAttribute("allApp",null);
                model.addAttribute("page",new int[]{1});
                model.addAttribute("currentPage",1);
                model.addAttribute("allPage",1);
            }else {
                PageInfo<AllApp> info=new PageInfo<>(allApp);
                model.addAttribute("allApp",info.getList());
                model.addAttribute("page",info.getNavigatepageNums());
                model.addAttribute("currentPage",info.getPageNum());
                model.addAttribute("allPage",info.getPages());
            }
        }

        return "sysUi/appSetting";
    }

    //删除应用
    @RequestMapping(value = "/removeApp",method = RequestMethod.POST)
    @ResponseBody
    public String removeApp(@RequestBody AllApp allApp,HttpSession session){
        if (!checkUser(session)){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        AllAppExample allAppExample=new AllAppExample();
        AllAppExample.Criteria criteria=allAppExample.createCriteria();
        criteria.andAppnameEqualTo(allApp.getAppname());
        int result=this.service.deleteApp(allAppExample);

        return JSONObject.toJSONString(result);
    }


    //更具应用名获取应用信息
    @RequestMapping(value = "/getApp",method = RequestMethod.POST)
    @ResponseBody
    public String getApp(HttpSession session){
        if (!checkUser(session)){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }

        AllAppExample allAppExample=new AllAppExample();
        AllAppExample.Criteria criteria=allAppExample.createCriteria();
        criteria.andHideEqualTo(0);
        criteria.andCanuseEqualTo(1);
        criteria.andDesktopEqualTo(1);

        List<AllApp> result=this.service.getAllApp(allAppExample);
        return JSONObject.toJSONString(result);
    }


    //添加或删除应用栏程序
    @RequestMapping(value = "/desktop",method = RequestMethod.POST)
    @ResponseBody
    public String removeApp(@RequestBody Info allApp,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }
        int result;
        AllApp allApp1=new AllApp();
        allApp1.setAppname(allApp.getName());
        allApp1.setId(allApp.getId());

        if (allApp.getType().equals("remove")){
            allApp1.setDesktop(0);
            result=this.service.updateApp(allApp1);
        }else {
            allApp1.setDesktop(1);
            result=this.service.updateApp(allApp1);
        }
        return JSONObject.toJSONString(result);
    }


    //=================================================用户管理Start============================================================
    //用户管理
    @RequestMapping(value = "/userAdmin",method = RequestMethod.GET)
    public String userAdmin(HttpServletRequest request,HttpSession session,Model model){
        if (!checkUser(session) || session==null){
            model.addAttribute("login","login");
        }else {
            int page=1;
            if (request.getParameter("page")!=null){
                page=Integer.parseInt(request.getParameter("page"));
            }
            PageHelper.startPage(page,14);

            UserExample userExample=new UserExample();
            UserExample.Criteria criteria=userExample.createCriteria();
            userExample.setOrderByClause("type");
            userExample.setOrderByClause("id");
            List<User> user=this.service.getUser(userExample);


            if (user.size()==0){
                model.addAttribute("user",null);
                model.addAttribute("page",new int[]{1});
                model.addAttribute("currentPage",1);
                model.addAttribute("allPage",1);
            }else {
                PageInfo<User> info=new PageInfo<>(user);
                model.addAttribute("user",info.getList());
                model.addAttribute("page",info.getNavigatepageNums());
                model.addAttribute("currentPage",info.getPageNum());
                model.addAttribute("allPage",info.getPages());
            }

        }


        return "sysUi/userAdmin";
    }

    //用户详情
    @RequestMapping(value = "/userDetail",method = RequestMethod.GET)
    public String userDetail(HttpServletRequest request,HttpSession session,Model model){
        if (!checkUser(session) || session==null){
            model.addAttribute("login","login");
        }else {
            String name=request.getParameter("name");
            UserExample example=new UserExample();
            UserExample.Criteria criteria=example.createCriteria();
            criteria.andNameEqualTo(name);
            List<User> users=this.service.getUser(example);
            model.addAttribute("user",users.get(0));
        }

        return "sysUi/userDetail";
    }

    //修改用户信息
    @RequestMapping(value = "/editUser",method = RequestMethod.POST)
    @ResponseBody
    public String userEdit(@RequestBody User user,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }



        String checkEdit = CheckNameAndEmail.checkNameAndEmailInfo(user,this.service,session);
        if (!checkEdit.equals("0")){
            return checkEdit;
        }


       try{
           int result=this.service.updateUser(user);
           if (result==1){
               return JSONObject.toJSONString(user);
           }else {
               return JSONObject.toJSONString(-30);
           }
       }catch (Exception e){
           return JSONObject.toJSONString(-30);
       }
    }

    //进入增加用户界面
    @RequestMapping(value = "/addUser",method = RequestMethod.GET)
    public String addUser(HttpServletRequest request,Model model,HttpSession session){
        if (!checkUser(session) || session==null){
            model.addAttribute("login","login");
        }else {

            if (request.getParameter("result")!=null){
                model.addAttribute("result",request.getParameter("result"));
            }
            List<Setting> list=this.service.getSetting(new SettingExample());
            model.addAttribute("config",list.get(0));
        }

        return "sysUi/addUser";
    }

    //提交添加用户申请
    @RequestMapping(value = "/addUserSubmit",method = RequestMethod.POST)
    public String addUserSubmit(HttpServletRequest request,Model moeditUserdel,RedirectAttributes attributes,HttpSession session){
        if (!checkUser(session) || session==null){
            return "sysUi/addUser";
        }else {
            int result=0;
            User user=new User();
            user.setCreatedate(new Date(System.currentTimeMillis()));
            user.setAddress(request.getParameter("address"));
            user.setAge(Integer.parseInt(request.getParameter("age")));
            user.setEducation(request.getParameter("education"));
            user.setName(request.getParameter("name"));
            user.setPassword(request.getParameter("password"));
            user.setType(request.getParameter("type"));
            user.setActivity(1);
            user.setSex(request.getParameter("sex"));
            user.setEmail(request.getParameter("email"));

            //检查是否存在该用户名的用户，存在则不添加
            UserExample userExample=new UserExample();
            UserExample.Criteria criteria=userExample.createCriteria();
            criteria.andNameEqualTo(user.getName());
            List<User> users=this.service.getUser(userExample);

            //获取是否存在该邮箱的用户，存在则不添加
            UserExample userEmail=new UserExample();
            UserExample.Criteria criteriaEmail=userEmail.createCriteria();
            criteriaEmail.andEmailEqualTo(user.getEmail());
            List<User> usersEmail=this.service.getUser(userEmail);

            if (users.size()!=0 && usersEmail.size()==0){
                result=-10;
                attributes.addAttribute("result",result);
                return "redirect:/futer/addUser";
            }
            if (usersEmail.size()!=0){
                result=-5;
                attributes.addAttribute("result",result);
                return "redirect:/futer/addUser";
            }

            result=this.service.addUser(user);
            attributes.addAttribute("result",result);
        }

        return "redirect:/futer/addUser";
    }

    //删除用户
    @RequestMapping(value = "/removeUser",method = RequestMethod.POST)
    @ResponseBody
    public String removeUser(@RequestBody User user,HttpSession session){
        if (!checkUser(session) || session==null){
            return JSONObject.toJSONString("请求被拒绝，无权访问");
        }

        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andNameEqualTo(user.getName());

        criteria.andIdEqualTo(user.getId());
        int result=this.service.deleteUser(userExample);
        return JSONObject.toJSONString(result);
    }

    //搜索用户
    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public String searchUser(@RequestBody Info info,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andNameEqualTo(info.getName());
        List<User> users=this.service.getUser(userExample);
        return JSONObject.toJSONString(users.get(0));
    }

    //禁用用户
    @RequestMapping(value = "/disableUser",method = RequestMethod.POST)
    @ResponseBody
    public String disableUser(@RequestBody Info info,HttpSession session){
        if (session.getAttribute("user")==null){
            return JSONObject.toJSONString("请求被拒绝，无权限访问");
        }
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andNameEqualTo(info.getName());
        System.out.println(info.getName());
        List<User> users=this.service.getUser(userExample);
        User user = users.get(0);
        if (user.getEnable()==1){
            user.setEnable(0);
        }else {
            user.setEnable(1);
        }
        int result = this.service.updateUser(user);
        return JSONObject.toJSONString("2");
    }

    //用户设置
    @RequestMapping(value = "/userSetting",method = RequestMethod.GET)
    public String userSetting(HttpServletRequest request,Model model,HttpSession session){
        if (!checkUser(session) || session==null){
            model.addAttribute("login","login");
        }else {
            if (request.getParameter("result")!=null){
                model.addAttribute("result",request.getParameter("result"));
            }
        }



        return "sysUi/userSetting";
    }

    //用户设置提交
    @RequestMapping(value = "/userSettingSub",method = RequestMethod.POST)
    public String userSettingSub(HttpServletRequest request,RedirectAttributes attributes,HttpSession httpSession,Model model){
        if (!checkUser(httpSession) || httpSession==null){
            model.addAttribute("login","login");
            return "sysUi/userSetting";
        }else {
            User user=new User();
            user.setCreatedate(new Date(System.currentTimeMillis()));
            user.setAddress(request.getParameter("address"));
            user.setAge(Integer.parseInt(request.getParameter("age")));
            user.setEducation(request.getParameter("education"));
            user.setEducation(request.getParameter("education"));
            user.setName(request.getParameter("name"));
            user.setPassword(request.getParameter("password"));
            user.setSex(request.getParameter("sex"));
            user.setId(((User)(httpSession.getAttribute("user"))).getId());


            int result=this.service.updateUser(user);
            if (result==1){
                httpSession.setAttribute("user",user);
            }
            attributes.addAttribute("result",result);
        }

        return "redirect:/futer/userSetting";
    }


    //=================================================用户管理End============================================================



    //设置验证码
    @Autowired
    public void setCaptchaProducer(Producer kaptchaProducer) {
        this.kaptchaProducer = kaptchaProducer;
    }

    @RequestMapping("/kaptcha")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response){
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = kaptchaProducer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = kaptchaProducer.createImage(capText);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("/register")
    public String register(HttpServletRequest request,HttpSession session,Model model){
        if (request.getParameter("error")!=null){
            model.addAttribute("name",request.getParameter("name"));
            model.addAttribute("email",request.getParameter("email"));
            model.addAttribute("password",request.getParameter("password"));
            model.addAttribute("error",request.getParameter("error"));
        }else {
            if (request.getParameter("email")!=null || request.getParameter("name")!=null || request.getParameter("password")!=null){
                model.addAttribute("name",request.getParameter("name"));
                model.addAttribute("email",request.getParameter("email"));
                model.addAttribute("password",request.getParameter("password"));
                model.addAttribute("statu",request.getParameter("statu"));
                System.out.println("其他");
            }
        }

        return "sysUi/register";
    }

    //注册新用户
    @RequestMapping(value = "/registerSubmit",method = RequestMethod.POST)
    public String registerSubmit(HttpServletRequest request, Model model, HttpSession session, RedirectAttributes attr) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        User user=new User();
        Date date = new Date(System.currentTimeMillis());
        user.setCreatedate(date);
        user.setName(name);
        user.setPassword(password);
        user.setType("user");
        user.setSex("未设置");
        user.setEmail(email);

        int result;
        //检测是否存在此用户名的用户
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andNameEqualTo(name);
        List<User> users=this.service.getUser(userExample);

        //检测是否存在此邮箱的用户
        UserExample userExampleCp=new UserExample();
        UserExample.Criteria criteriaCp=userExampleCp.createCriteria();
        criteriaCp.andEmailEqualTo(email);
        List<User> usersCp=this.service.getUser(userExampleCp);

        if (users.size()>0){
            attr.addAttribute("error","用户名已存在");
            return "redirect:/futer/register";
        }if (usersCp.size()>0){
            attr.addAttribute("error","邮箱已被注册");
            return "redirect:/futer/register";
        }else{

            //添加用户操作
            result=this.service.addUser(user);

            //判断是否添加成功
            if (result==1){
                //发送邮件
                String status = SendEmail.sengEmail(email,date,name,"注册");
                attr.addAttribute("name",name);
                attr.addAttribute("password",password);
                attr.addAttribute("email",email);

                //判断是否发送邮件成功
                if (status.equals("success")){
                    attr.addAttribute("statu","success");
                    model.addAttribute("registerAlert","邮件发送成功，请注意查收。");
                    return "sysUi/loginview";
                }else {
                    attr.addAttribute("statu","false");
                    return "redirect:/futer/register";
                }
            }else {
                attr.addAttribute("error","用户注册失败");
                return "redirect:/futer/register";
            }

        }

    }


    //激活用户
    @RequestMapping(value = "/makeActivity")
    public String makeActicity(HttpServletRequest request,HttpServletResponse response,Model model){
        String key = request.getParameter("key");
        String name = request.getParameter("name");

        //查询用户
        UserExample user = new UserExample();
        UserExample.Criteria criteria =user.createCriteria();
        criteria.andCreatedateEqualTo(new Date(Long.parseLong(key)));
        criteria.andNameEqualTo(name);
        List<User> us = this.service.getUser(user);

        if (us.size() == 0){
            model.addAttribute("info","0");
        }else {
            //将激活标记设置为激活状态
            if (us.get(0).getActivity()==1){
                model.addAttribute("info","-1");
            }else {
                User tempUser = us.get(0);
                tempUser.setActivity(1);
                this.service.updateUser(tempUser);
                model.addAttribute("info","1");
            }
        }
        return "sysUi/makeActivity";
    }

    //进入忘记密码界面
    @RequestMapping(value = "/forgetPwd")
    public String forgetPwd(HttpServletRequest request,Model model){
        if (request.getParameter("status")!=null){
            model.addAttribute("status",request.getParameter("status"));
            model.addAttribute("email",request.getParameter("email"));
        }
        return "sysUi/forgetPwd";
    }

    //提交忘记密码的内容
    @RequestMapping(value = "/forgetPwdSubmid",method = RequestMethod.POST)
    public String forgetPwdSubit(HttpServletRequest request,HttpServletResponse response,RedirectAttributes attributes){
        String email = request.getParameter("email");
        String pwd = request.getParameter("pwd");
        String rePwd = request.getParameter("rePwd");
        String code = request.getParameter("code");

        String result=null;
        Date date = new Date();
        String databaseCode = GetRandWord.getRandWord();
        int delete = 0;
        if (email!=null && pwd==null && rePwd==null && code==null){

            //获取此邮件的用户信息
            UserExample userExample = new UserExample();
            UserExample.Criteria userExamp = userExample.createCriteria();
            userExamp.andEmailEqualTo(email);
            List<User> userList = this.service.getUser(userExample);
            if (userList==null || userList.size()==0){
                attributes.addAttribute("email", email);
                attributes.addAttribute("status", "用户尚未注册");
                return "redirect:/futer/forgetPwd";
            }

            if (userList!=null && userList.size()>0){
                if (userList.get(0).getActivity()==0){
                    attributes.addAttribute("email", email);
                    attributes.addAttribute("status", "用户账号尚未激活或已被禁用");
                    return "redirect:/futer/forgetPwd";
                }
            }

            //获取数据库验证码
            IdentifyingCodeExample identifyingCodeExample = new IdentifyingCodeExample();
            IdentifyingCodeExample.Criteria criteria = identifyingCodeExample.createCriteria();
            criteria.andEmailEqualTo(email);
            IdentifyingCode exist = this.service.getCode(email);

            if (exist!=null){
                //如果数据库存在邮件且还没过期，则不进行邮件发送，而是提示用户检查邮箱
                if (exist.getDate().getTime() + 600000 < date.getTime()) {
                    attributes.addAttribute("email", email);
                    attributes.addAttribute("status", "邮件已经发送给，请检查您的邮箱");
                    return "redirect:/futer/forgetPwd";
                }else {
                    //获取数据库中是否存在此账号的验证码，存在则删除
                    delete = this.service.deleteCode(email);
                }
            }

            String status = SendEmail.sengEmail(email,date,databaseCode,"验证码");
            if (status.equals("success")){


                if ((delete==1 && exist!=null) || exist==null){
                    //向数据库插入验证码
                    IdentifyingCode identifyingCode = new IdentifyingCode();
                    identifyingCode.setCode(databaseCode);
                    identifyingCode.setEmail(email);
                    identifyingCode.setDate(date);
                    int insert = this.service.addCode(identifyingCode);

                    //到这步说明邮件已发送且数据库插入成功
                    if (insert==1){
                        result = "邮件发送成功";
                    }else {
                        result = "邮件发送失败";
                    }
                }else {
                    result = "数据库存储失败";
                }
            }else {
                result = "邮件发送失败";
            }

        }else {
            if (pwd==null || rePwd==null || code==null){
                return "redirect:/futer/forgetPwd";
            }
            IdentifyingCode identifyingCode = this.service.getCode(email);
            if (identifyingCode!=null){
                if (identifyingCode.getDate().getTime()<=date.getTime()+600000){
                    if (identifyingCode.getCode().equals(code)){
                        //获取用户
                        UserExample userExample = new UserExample();
                        UserExample.Criteria criteria = userExample.createCriteria();
                        criteria.andEmailEqualTo(email);
                        List<User> user = this.service.getUser(userExample);

                        //修改密码
                        if (user.size()==1 && user!=null){
                            User us = user.get(0);
                            us.setPassword(pwd);
                            int update=this.service.updateUser(us);
                            if (update!=1){
                                attributes.addAttribute("email",email);
                                attributes.addAttribute("status","密码修改失败");
                                return "redirect:/futer/forgetPwd";
                            }
                        }

                        //删除数据库验证码
                        this.service.deleteCode(email);

                        attributes.addAttribute("successChangePwd","密码修改成功");
                        return "sysUi/loginview";
                    }else {
                        result = "验证码输入不正确";
                    }
                }else {
                    result = "验证码已过期";

                    //过期后删除过期的验证码
                    int de = this.service.deleteCode(email);
                }
            }else {
                result = "验证码不存在";
            }
        }
        attributes.addAttribute("email",email);
        attributes.addAttribute("status",result);
        return "redirect:/futer/forgetPwd";
    }


    //应用列表
    @RequestMapping(value = "/appMenu")
    public String appMenu(HttpServletRequest request,HttpServletResponse response,Model model,HttpSession session){
        if (session==null || session.getAttribute("user")==null){
            model.addAttribute("login","login");
        }else {
            //获取应用列表
            User user = (User)session.getAttribute("user");
            AllAppExample allAppExample = new AllAppExample();
            AllAppExample.Criteria criteria = allAppExample.createCriteria();
            if (!user.getType().equals("admin")){
                criteria.andToadminEqualTo(0);
            }
            List<AllApp> allApps = this.service.getAllApp(allAppExample);
            model.addAttribute("appMenu",allApps);
        }

        return "sysUi/appMenu";
    }

    //应用详情及编辑
    @RequestMapping(value = "/appEdit")
    public String appDetail(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model model){
        if (session==null || session.getAttribute("user")==null){
            model.addAttribute("login","login");
        }else {
            String name = request.getParameter("name");
            AllAppExample allAppExample = new AllAppExample();
            AllAppExample.Criteria criteria = allAppExample.createCriteria();
            criteria.andAppnameEqualTo(name);
            List<AllApp> app = this.service.getAllApp(allAppExample);
            model.addAttribute("app",app.get(0));
        }

        return "sysUi/appDetail";
    }

    //保存应用的修改
    @RequestMapping(value = "/appsetting/save")
    @ResponseBody
    public String saveSetting(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody PostSetting setting){
        AllAppExample allAppExample = new AllAppExample();
        AllAppExample.Criteria criteria = allAppExample.createCriteria();
        criteria.andAppnameEqualTo(setting.getName());
        List<AllApp> allApps = this.service.getAllApp(allAppExample);

        AllAppExample allUrl = new AllAppExample();
        AllAppExample.Criteria criteriaUrl = allUrl.createCriteria();
        criteriaUrl.andAppnameEqualTo(setting.getName());
        List<AllApp> allAppUrl = this.service.getAllApp(allUrl);

        if (allApps.size()>=2){
            return JSONObject.toJSONString("此应用名称已存在");
        }

        if (allAppUrl.size()>=2){
            return JSONObject.toJSONString("已存在此URL地址");
        }

        AllApp allApp = new AllApp();

        if (allApps.size()==1 && allApps.get(0).getAppname().equals(setting.getName())){
            allApp.setAppname(setting.getName());
        }else if (allApps.size()==0){
            allApp.setAppname(setting.getName());
        }

        if (allAppUrl.size()==1 && allAppUrl.get(0).getAppurl().equals(setting.getUrl())){
            allApp.setAppurl(setting.getUrl());
        }else if (allAppUrl.size()==0){
            allApp.setAppurl(setting.getUrl());
        }

        return null;
    }
}